<template>
  <div>
    <div :id="tid" class="tmap-content"></div>
    <h4>
      地址信息: {{ address }}
    </h4>
  </div>
</template>

<script>

export default {
  props: {
    /**
     * 经度
     */
    longitude: {
      type: Number,
      required: true,
    },
    /**
     * 纬度
     */
    latitude: {
      type: Number,
      required: true,
    },
    address: {
      type: String,
      default: ''
    },
    tid: {
      type: String,
      default: 'tmap'
    }
  },
  data () {
    return {
      map: null,
      marker: null,
      popup: null,
      sfCodingQuery: null,
      sfRGeoCodingQuery: null,
      value: "",
      // 地址信息
      addressInfo: {
        name: "",
        detail: "",
        longitude: 0,
        latitude: 0,
      },
      show: false,
    };
  },
  mounted () {
    this.loadScripts();
  },
  created () {
  },
  watch: {
    mapAndlngLat: {
      handler (newVal) {
        const { map, longitude, latitude, sfRGeoCodingQuery } = newVal || {};
        if (map && longitude && latitude && sfRGeoCodingQuery) {
          this.getAddressByLngLat({
            x: longitude,
            y: latitude,
          })?.then(() => {
            this.setPonit([longitude, latitude]);
          });
        }
      },
      immediate: true,
    },
  },
  computed: {
    mapAndlngLat () {
      return {
        map: this.map,
        longitude: this.longitude,
        latitude: this.latitude,
        address: this.address,
        sfRGeoCodingQuery: this.sfRGeoCodingQuery,
      };
    },
  },

  methods: {
    loadScripts () {
      const wgs84_wgs84_mapcrs = {
        topTileExtent: [-180, -270, 180, 90],
        tileSize: 256,
      };

      // 构造地图对象实例,并添加到id为map的div容器中
      this.map = new window.GeoGlobe.Map({
        container: this.tid, //绑定容器
        mapCRS: wgs84_wgs84_mapcrs, //定义坐标系
        zoom: 13, //当前缩放级别
        center: [118.778, 31.843], //定位中心点
        maxZoom: 20, //最大缩放级别
        minZoom: 10, //最小缩放级别
      });

      if (this.map) {
        this.map.on("load", () => {
          var wmts = new window.GeoGlobe.Format.WMTS();
          //加载注记
          let zj_url = "http://58.213.148.61:8089/geostar/JNTDT_ZJ/wmts";
          var zj_layer = wmts.createLayer(zj_url);
          //加载地图
          let dt_url = "http://58.213.148.61:8089/geostar/JNTDT_DT/wmts";
          var dt_layer = wmts.createLayer(dt_url);

          // 添加图层
          this.map.addLayer(dt_layer);
          this.map.addLayer(zj_layer);

          // 控制版
          const Na_control = new window.GeoGlobe.Control.Navigation();
          this.map.addControl(Na_control, "top-left");

          // 逆地名地址查询实例
          this.sfRGeoCodingQuery =
            new window.GeoGlobe.Query.SFRGeoCodingQuery();
        });
      }
    },
    /**
      * @param {number} x longitude
      * @param {number} y latitude
      */
    getAddressByLngLat ({ x, y }) {
      var that = this
      return new Promise((resolve, reject) => {
        if (this.sfRGeoCodingQuery) {
          this.sfRGeoCodingQuery.query({ x, y }, function (result) {
            console.log("result: ", result)
            if (result.msg) {
              reject("没有查询到结果。");
            } else {
              const detail = result.name;
              const longitude = result.pois?.[0]?.x;
              const latitude = result.pois?.[0]?.y;
              that.show = true;
              //  TODO
              //  减少误差，如果误差过大，则不能认为是同一个位置（存疑，未验证）
              //  300米？
              if (
                Math.abs(longitude - result?.my_x) <= 0.003 &&
                Math.abs(latitude - result?.my_y) <= 0.003
              ) {
                that.addressInfo = {
                  name: result.pois?.[0]?.name,
                  detail,
                  longitude,
                  latitude,
                };
              } else {
                that.addressInfo = {
                  name: "",
                  detail,
                  longitude: result.my_x,
                  latitude: result.my_y,
                };
              }
              resolve(that.addressInfo);
            }
          });
        }
      });
    },
    setPonit ([longitude, latitude]) {
      if (this.marker) {
        this.marker?.setLngLat([longitude, latitude]);
      } else {
        this.marker = new window.GeoGlobe.Marker()
          .setLngLat([longitude, latitude])
          .addTo(this.map); //添加mark到地图上
      }
      this.map.flyTo({
        center: [longitude, latitude],
        zoom: 13,
      });
    },
  }

};

</script>

 

<style scoped>
.tmap-content {
  width: 100vw;
  height: 90vh;
}
</style>